from django.db.models import Q, Exists
from django.shortcuts import render

from django.contrib.auth.hashers import make_password, check_password
from django.http import JsonResponse, HttpResponse
from ..models import *
from ..utils import jwtUtils
from ..utils.fileSystem import removeFile, uploadFileAssets
from ..utils.func import filterImageUrl, getCurrentDate, filterDataListImageUrl, getCurrentTime, filterBodyList, \
    getDecimalData
from ..utils.jsonSerialize import serialize_models
import time

from ..utils.paramsValidator import RulesValidate


# 一、个人中心
# 用户详情
def userAbout(request):
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    user_obj = UserMsg.objects.filter(id=user_id).first()
    # 序列化数据集对象
    user_obj = serialize_models(user_obj)
    filterImageUrl(request,user_obj,'avatar_url')
    # 获取优惠券汇总
    # 获取当前时间
    currentDate = getCurrentDate()
    request_Data = {}
    request_Data["coupon_user_id"] = user_id
    request_Data["start_time__lte"] = currentDate
    request_Data["end_time__gte"] = currentDate
    request_Data["status"] = '1'
    count = Coupons.objects.filter(**request_Data).count()
    user_obj['coupon'] = count
    return JsonResponse ({'msg': '获取个人信息成功 ！', 'data': user_obj, 'code': 200})

# 修改信息
def userUpdate(request):
    data = request.POST.dict ()
    data.pop("password",None)
    data.pop("avatar_url",None)
    # 添加修改时间
    data['update_time'] = time.strftime ('%Y-%m-%d %H:%M:%S', time.localtime ())
    data['is_delete'] = '0'
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    user_obj = UserMsg.objects.filter (id=user_id)
    user_obj.update(**data)
    return JsonResponse ({'msg': '更新用户信息成功！', 'code': 200})

# 修改密码
def updatePassword(request):
    data = request.POST.dict ()
    # 添加修改时间
    data['update_time'] = time.strftime ('%Y-%m-%d %H:%M:%S', time.localtime ())
    data['is_delete'] = '0'
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    user_obj = UserMsg.objects.filter (id=user_id)
    user_obj_filter = user_obj.first()

    # 检测旧密码是否相同
    res = check_password (data['old_password'], user_obj_filter.password)
    if not res:
        return JsonResponse ({'msg': '输入的旧密码错误！请重新输入！', 'code': 403})
    else:
        # 加密新密码
        data['password'] = make_password (data['new_password'], None, 'pbkdf2_sha256')
        del data['old_password']
        del data['new_password']
        user_obj.update(**data)
        return JsonResponse ({'msg': '更新登录密码成功！', 'code': 200})

# 修改密码
def updateAvatar(request):
    # data = request.POST.dict ()
    data = {}
    # 添加修改时间
    data['update_time'] = time.strftime ('%Y-%m-%d %H:%M:%S', time.localtime ())
    data['is_delete'] = '0'

    # 如果有头像上传，则保存头像。
    filename = uploadFileAssets(request, 'avatar')
    if filename == None:
        return JsonResponse ({'msg': '更新失败！上传的图片不能为空', 'code': 403})

    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    user_obj = UserMsg.objects.filter (id=user_id)
    user_obj_filter = user_obj.first()
    if user_obj_filter == None:
        return JsonResponse ({'msg': '当前用户不存在！', 'code': 403})
    print(user_obj_filter)
    if user_obj_filter.avatar_url != None:
        removeFile(user_obj_filter.avatar_url)
    data['avatar_url'] = filename
    user_obj.update(**data)
    return JsonResponse ({'msg': '更新头像成功！','data': filename, 'code': 200})


# 二、每日通知
# 获取通知
def noticeList(request):
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    current_date = getCurrentDate()
    # data = request.GET.dict ()
    # title = data.get('title',None)
    # user_id = data.get('user_id', None)
    # start_time = data.get('start_time', None)
    # end_time = data.get('end_time', None)
    request_Data = {}
    request_Data['end_time__gte'] = current_date
    data_list = Notices.objects.filter(Q(**request_Data) & (Q(notice_user_id=user_id) | Q(notice_user_id__isnull=True)))
    data_list = serialize_models(data_list)
    # # 对图片信息进行处理
    filterDataListImageUrl(request,data_list,'notice_url')
    # 用户信息
    user_obj = UserMsg.objects.filter(id=user_id).first()
    # 序列化数据集对象
    user_obj = serialize_models(user_obj)
    filterImageUrl(request,user_obj,'avatar_url')
    return JsonResponse ({'msg': '获取通知成功！','data': { 'notice_list': data_list, 'userinfo': user_obj }, 'code': 200})


# 三、选品商城
# 获取商品
def shopIndex(request):
    data = request.GET.dict ()
    name = data.get('name',None)
    start_price = data.get('start_price',None)
    end_price = data.get('end_price',None)
    page_num = int(data.get('page_num',1))
    page_size = int(data.get('page_size',10))
    request_Data = {}
    request_Data["status"] = '1'
    request_Data["max_count__gt"] = 0
    if start_price:
        request_Data["price__gte"] = start_price
    if end_price:
        request_Data["price__lte"] = end_price
    # 计算索引
    start_index = (page_num - 1) * page_size
    end_index = page_num * page_size
    # 执行获取
    data_list = None
    if name:
        # request_Data["name__icontains"] = name
        # request_Data["keywords__icontains"] = name
        data_list = Goods.objects.filter(Q(**request_Data) & (Q(name__icontains=name) | Q(keywords__icontains=name) | Q(description__icontains=name)))
    else:
        data_list = Goods.objects.filter(**request_Data)
    count = data_list.count()
    data_list = serialize_models(data_list[start_index: end_index])
    # 对图片信息进行处理
    filterDataListImageUrl(request,data_list,'banner_url')
    return JsonResponse ({'msg': '获取商品信息成功！','data': { 'data_list': data_list, 'count': count }, 'code': 200})


# 商品详情
def shopGoodsInfo(request):
    data = request.GET.dict()
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    data.pop("csrfmiddlewaretoken", None)
    # 验证请求参数
    res = RulesValidate(request,'GET',{
        'id': '商品Id',
    })
    if res: return res
    # 先检测数据表
    goods_obj = Goods.objects.filter(id=data['id'])
    goods_obj_filter = goods_obj.first()
    if not goods_obj_filter:
        return JsonResponse({'msg': '获取失败！商品不存在！', 'code': 403})
    else:
        # 序列化数据集对象
        goods_obj_filter = serialize_models(goods_obj_filter)
        filterImageUrl(request, goods_obj_filter, 'banner_url')
        # 获取评论信息
        comments_data_list = GoodsComment.objects.filter(goods_id=data['id']).all()
        # 序列化数据集对象
        comments_data_list = serialize_models(comments_data_list,['user'])
        filterDataListImageUrl(request,comments_data_list,'avatar_url','user')
        # 清除字段
        for item in comments_data_list:
            try:
                del item['user']['password']
                del item['user']['token']
            except:
                pass
        # 获取当前用户的评论信息
        comment_obj = GoodsComment.objects.filter(goods_id=data['id'], user_id=user_id)
        comment_obj_filter = comment_obj.first()
        comment_obj_filter = serialize_models(comment_obj_filter)
        return JsonResponse({'msg': '获取商品详情成功！','data': { 'goods_info': goods_obj_filter, 'comment_list': comments_data_list, 'my_comment': comment_obj_filter }, 'code': 200})

# 四、评论相关
# 新增评论
def commentAdd(request):
    data = request.POST.dict()
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'goods_id': '商品id',
        'star': '商品评星',
        'content': '内容',
    })
    if res: return res
    # 先检测数据表
    goods_obj = Goods.objects.filter(id=data['goods_id'])
    goods_obj_filter = goods_obj.first()
    if not goods_obj_filter:
        return JsonResponse({'msg': '评论失败！商品不存在！', 'code': 403})
    # 如果有评论，则不允许多次评论
    comment_obj = GoodsComment.objects.filter(goods_id=data['goods_id'],user_id=user_id)
    comment_obj_filter = comment_obj.first()
    if comment_obj_filter != None:
        return JsonResponse({'msg': '您已经评论了该商品，无法重复评论！', 'code': 403})
    # 添加创建时间
    data['create_time'] = getCurrentTime()
    data['user_id'] = user_id
    resObj = GoodsComment(**data)
    resObj.save()
    if resObj.id != None:
        return JsonResponse ({'msg': '新增评论成功！', 'code': 200})
    else:
        return JsonResponse ({'msg': '新增评论失败！请重试', 'code': 200})

# 修改评论
def commentUpdate(request):
    data = request.POST.dict()
    data.pop("csrfmiddlewaretoken", None)
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'goods_id': '商品id',
        'star': '商品评星',
        'content': '内容',
        'id': '评论id',
    })
    if res: return res
    # 先检测数据表
    goods_obj = Goods.objects.filter(id=data['goods_id'])
    goods_obj_filter = goods_obj.first()
    if not goods_obj_filter:
        return JsonResponse({'msg': '修改失败！商品不存在！', 'code': 403})
    # 先检测数据表
    comment_obj = GoodsComment.objects.filter(id=data['id'],goods_id=data['goods_id'])
    comment_obj_filter = comment_obj.first()
    # 添加注更新时间
    data['update_time'] = getCurrentTime()
    data['user_id'] = user_id
    if not comment_obj_filter:
        return JsonResponse({'msg': '修改失败！评论不存在！', 'code': 403})
    else:
        comment_obj.update(**data)
        return JsonResponse({'msg': '修改评论成功！', 'code': 200})

# 删除评论
def commentDelete(request):
    data = request.POST.dict ()
    # 验证请求参数
    res = RulesValidate(request, 'POST', {
        'id': '评论id',
    })
    if res: return res
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    user_obj = UserMsg.objects.filter(id=user_id).first()
    # 如果当前用户是(0为禁用，1为正常，2为管理员),普通用户则只能删除自己的信息
    if user_obj.type == '1':
        data['user_id'] = user_id
    comment_obj = GoodsComment.objects.filter(**data)
    comment_obj_filter = comment_obj.first()
    if comment_obj_filter == None:
        return JsonResponse({'msg': '评论不存在或无权限删除！', 'code': 403})
    # # 序列化数据
    # data_list = serialize_models(comment_obj)
    res = comment_obj.delete()
    if res[0] > 0:
        return JsonResponse({'msg': '删除评论成功！', 'code': 200})
    else:
        return JsonResponse({'msg': '数据不存在或已删除！', 'code': 200})


# 五、购物车
# 购物车列表
def cartList(request):
    data = request.GET.dict ()
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    data_list = Carts.objects.filter(user_id=user_id)
    data_list = serialize_models(data_list)
    # 对图片信息进行处理
    filterDataListImageUrl(request,data_list,'banner_url')
    return JsonResponse ({'msg': '获取购物车信息成功！','data': data_list, 'code': 200})

# 添加购物车
def cartAdd(request):
    data = request.POST.dict()
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'goods_id': '商品id',
        'goods_count': '商品数量',
    })
    if res: return res
    # 更新商品数量
    data['goods_count'] = int(data['goods_count'])
    if data['goods_count'] < 1:
        return JsonResponse({'msg': '添加购物车失败！数量至少为1！', 'code': 403})
    # 先检测数据表
    goods_obj = Goods.objects.filter(id=data['goods_id'])
    goods_obj_filter = goods_obj.first()
    if not goods_obj_filter:
        return JsonResponse({'msg': '添加购物车失败！商品不存在！', 'code': 403})
    if goods_obj_filter.max_count < data['goods_count']:
        return JsonResponse({'msg': '添加购物车失败！商品库存不足！', 'code': 403})
    # 更新购物车商品信息
    data['banner_url'] = goods_obj_filter.banner_url
    data['goods_name'] = goods_obj_filter.name
    data['goods_price'] = goods_obj_filter.price
    # 如果有购物车，则不允许多次购物车
    cart_obj = Carts.objects.filter(goods_id=data['goods_id'],user_id=user_id)
    cart_obj_filter = cart_obj.first()
    if cart_obj_filter != None:
        # 添加更新时间
        data['update_time'] = getCurrentTime()
        cart_obj.update(**data)
        # 更新购物车商品
        return JsonResponse({'msg': '添加购物车成功！', 'code': 200})
    else:
        # 新增购物车商品
        # 添加创建时间
        data['create_time'] = getCurrentTime()
        data['user_id'] = user_id
        resObj = Carts(**data)
        resObj.save()
        if resObj.id != None:
            return JsonResponse ({'msg': '添加购物车成功！', 'code': 200})
        else:
            return JsonResponse ({'msg': '添加购物车失败！请重试', 'code': 200})

# 修改购物车
def cartUpdate(request):
    data = request.POST.dict()
    data.pop("csrfmiddlewaretoken", None)
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'id': '购物车id',
        'goods_count': '商品数量',
    })
    if res: return res
    # 更新商品数量
    data['goods_count'] = int(data['goods_count'])
    # 先检测数据表
    cart_obj = Carts.objects.filter(id=data['id'])
    cart_obj_filter = cart_obj.first()
    if not cart_obj_filter:
        return JsonResponse({'msg': '更新失败！购物车商品不存在！', 'code': 403})
        # 先检测数据表
    goods_obj = Goods.objects.filter(id=cart_obj_filter.goods_id)
    goods_obj_filter = goods_obj.first()
    goods_info = serialize_models(goods_obj_filter)
    if not goods_obj_filter:
        return JsonResponse({'msg': '更新失败！商品不存在！', 'code': 403})
    if goods_obj_filter.max_count < data['goods_count']:
        return JsonResponse({'msg': f'更新失败！商品库存不足,商品库存为{goods_obj_filter.max_count}.', 'code': 403})
    # 更新购物车商品信息
    data['banner_url'] = goods_obj_filter.banner_url
    data['goods_name'] = goods_obj_filter.name
    data['goods_price'] = goods_obj_filter.price
    cart_obj.update(**data)
    return JsonResponse({'msg': '修改成功！','goods_info': goods_info, 'code': 200})

# 移除购物车
def cartDelete(request):
    data = request.POST.dict ()
    # 验证请求参数
    res = RulesValidate(request, 'POST', {
        'id': '购物车id',
    })
    if res: return res
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    data['user_id'] = user_id
    cart_obj = Carts.objects.filter(**data)
    cart_obj_filter = cart_obj.first()
    if cart_obj_filter == None:
        return JsonResponse({'msg': '数据不存在或已移除！', 'code': 403})
    # # 序列化数据
    # data_list = serialize_models(cart_obj)
    res = cart_obj.delete()
    if res[0] > 0:
        # 移除图片
        return JsonResponse({'msg': '移除购物车成功！', 'code': 200})
    else:
        return JsonResponse({'msg': '数据不存在或已移除！', 'code': 200})


# 提交购物车兑换
def cartSubmit(request):
    data = request.POST.dict()
    data.pop("csrfmiddlewaretoken", None)
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    # 获取当前时间
    currentDate = getCurrentDate()
    currentTime = getCurrentTime()
    # 验证请求参数
    res = RulesValidate(request,'POST',{
        'cart_id_list': '购物车id',
    })
    coupon_id = data.get('coupon_id',None)
    if res: return res
    cart_id_list= filterBodyList(data['cart_id_list'])
    # 先检测数据表
    cart_obj = Carts.objects.filter(id__in=cart_id_list)
    # 格式化数据
    cart_list = serialize_models(cart_obj)
    cart_obj_filter = cart_obj.first()
    if not cart_obj_filter:
        return JsonResponse({'msg': '提交失败！购物车商品不能为空！', 'code': 403})
    # 合计数据amount,count
    amount = 0
    count = 0
    for item in cart_list:
        # 检查当前商品的价格和数量
        goods_obj = Goods.objects.filter(id=item['goods_id'])
        goods_obj_filter = goods_obj.first()
        if goods_obj_filter == None:
            return JsonResponse({'msg': f'提交失败！购物车商品:{item["goods_name"]}不存在！', 'code': 403})
        if goods_obj_filter.max_count < item['goods_count']:
            return JsonResponse({'msg': f'提交失败！购物车商品:{item["goods_name"]}库存不足，只剩余{goods_obj_filter.max_count}！', 'code': 403})
        # 合计金额
        amount += float(goods_obj_filter.price) * item['goods_count']
        count += item['goods_count']
    after_amount = amount
    coupon_amount = 0
    # 检测当前用户的余额
    user_obj = UserMsg.objects.filter(id=user_id)
    user_obj_filter = user_obj.first()
    # 当前用户访问成功，则一定是存在的
    if user_obj_filter.amount <= 0:
        return JsonResponse({'msg': '您的余额已不足，无法进行兑换', 'code': 403})
    # 先检测优惠券
    if coupon_id:
        coupon_obj = Coupons.objects.filter(id=coupon_id)
        coupon_obj_filter = coupon_obj.first()
        if coupon_obj_filter == None:
            return JsonResponse({'msg': '优惠券不存在！无法提交', 'code': 403})
        if coupon_obj_filter.status != '1':
            return JsonResponse({'msg': '优惠券已使用或已过期！无法提交', 'code': 403})
        if str(coupon_obj_filter.end_time) < currentDate:
            return JsonResponse({'msg': '优惠券已过期！无法提交', 'code': 403})
        if coupon_obj_filter.level_price > getDecimalData(amount):
            return JsonResponse({'msg': '当前订单没有达到优惠券门槛！无法提交', 'code': 403})
        # 更新优惠券状态（不考虑处理结果）
        res1 = coupon_obj.update(status=2)
        # 扣除优惠金额
        after_amount -= float(coupon_obj_filter.value)
        coupon_amount = float(coupon_obj_filter.value)
    # 新增兑换头
    data_head = {
        'user_id': user_id,
        'amount': amount,
        'count': count,
        'coupon_amount': coupon_amount,
        'coupon_id': coupon_id,
        'after_amount': after_amount,
        'status': '0',
        'create_time': currentTime
    }
    resObj = Exchanges(**data_head)
    resObj.save()
    if resObj.id != None:
        # 更新商品库存
        exchange_goods_list = []
        for item in cart_list:
            try:
                # 检查当前商品的价格和数量（不考虑同步性问题）
                goods_obj = Goods.objects.filter(id=item['goods_id'])
                goods_obj_filter = goods_obj.first()
                max_count = goods_obj_filter.max_count - item['goods_count']
                goods_obj.update(max_count=max_count)
                # 获取兑换商品数据
                data_body = {
                    'user_id': user_id,
                    'exchange_id': None,
                    'goods_id': goods_obj_filter.id,
                    'banner_url': goods_obj_filter.banner_url,
                    'goods_name': goods_obj_filter.name,
                    'goods_price': goods_obj_filter.price,
                    'goods_count': item['goods_count'],
                    'goods_amount': float(goods_obj_filter.price) * item['goods_count'],
                    'create_time': currentTime
                }
                exchange_goods_list.append(data_body)
            except:
                pass
        # 新增兑换商品数据
        for item in exchange_goods_list:
            try:
                item['exchange_id'] = resObj.id
                # 不考虑新增结果
                ExchangeGoods(**item).save()
            except:
                pass
        # 购物车商品去除
        res2 = cart_obj.delete()
        return JsonResponse({'msg': '提交成功！请等待兑换','code': 200})
    else:
        return JsonResponse({'msg': '提交失败！请重试', 'code': 200})


# 查询可用优惠券
def cartCouponList(request):
    data = request.POST.dict ()
    # 获取当前时间
    currentDate = getCurrentDate()
    # 获取请求头上的token,转换成user_id
    user_id = jwtUtils.get_parse_token(request)
    amount = data.get('amount',None)
    status = data.get('status',None)
    request_Data = {}
    request_Data["coupon_user_id"] = user_id
    request_Data["start_time__lte"] = currentDate
    request_Data["end_time__gte"] = currentDate
    date_list = None
    # 如果有总金额，则查看当前金额符合最低门槛
    if amount:
        request_Data["level_price__lte"] = getDecimalData(amount)
    # 如果没有状态传递，则不允许是已撤销的优惠券
    if status:
        request_Data["status"] = status
        data_list = Coupons.objects.filter(**request_Data).order_by('-value','-level_price')
    else:
        data_list = Coupons.objects.filter(Q(**request_Data) & (~Q(status=0))).order_by('-value','-level_price')
    data_list = serialize_models(data_list)
    # 对图片信息进行处理
    filterDataListImageUrl(request,data_list,'coupon_url')
    return JsonResponse ({'msg': '获取优惠券信息成功！','data':data_list, 'code': 200})
